<template>
<div>
  <div class="pusherNetStatus">
    <p>liveMessage:{{liveMessage}}</p>
    <p>liveCode:{{liveCode}}</p>

  </div>
  <live-pusher id='livePusher' ref="livePusher" class="livePusher" :url="pushUrl" :mode="coderate"
               :beauty="isBeautiful" :whiteness="whitenessLevel" aspect="9:16" @statechange="statechange"
               @netstatus="netstatus" @error="error" enable-agc="true" enable-ans="true"
               :style="{width:pushWidth+'px',height:pushHeight+'px'}"></live-pusher>

  <scroll-view class="liveSayWrap" scroll-y="true" :scroll-top="scrollTop" @scrolltolower="scrolltolower"
               scroll-with-animation="true" @scroll="scroll"
               :scroll-into-view="scrollIntoView">
    <div class="tipwrap">
      {{ systemNotice }}
    </div>
    <div v-for="(item, index) in msgList" :key="index" @click="showActive(item)" class="item" :id="'A'+index">
      <div :id="'msg-' + index" class="item-item" :class="[item.username ? 'tip-scroller__msg--active' : '']">
        <text class="tip-scroller__tag tip-scroller__member" v-if="item.member_rank">{{ item.member_rank ? item.member_rank : '' }}</text>
        <text class="tip-scroller__tag" v-if="item.username">{{ item.username ? item.rank : '' }}</text>
        <p class="username" style="font-size: 16px;">
          {{ item.username ? item.username + ': ' : '' }}
        </p>

        <text class="" style="font-size: 16px;" v-for="(text, i) in item.msg" :key="i"> {{ text }}</text>
      </div>

    </div>
  </scroll-view>

  <div class="footerWrap">
    <div @click="switchCamera" class="buticon martp10">

      <u-icon name="/static/images/live/icon-transform.png" color="#fff" size="58" label="翻转"
              label-pos="bottom" label-color="#fff"></u-icon>

    </div>
    <div class="buticon martp10" @click="snapshot">

      <u-icon name="/static/images/live/icon-screeShot.png" color="#fff" size="58" label="快照"
              label-pos="bottom" label-color="#fff"></u-icon>
    </div>
    <div class="buticon martp10" @click="startPusher">

      <u-icon :name="isPlay?'pause-circle':'play-circle'" :color="isPlay?'red':'#fff'" size="58"
              :label="isPlay?'暂停':'开播'" label-pos="bottom" label-color="#fff"></u-icon>
    </div>
    <div class="buticon martp10" @click="changewhiteness">
      <u-icon name="woman" color="'#fff" size="58" label="美白" label-pos="bottom" label-color="#fff"></u-icon>

    </div>
    <div class="buticon martp10" @click="beautiful">
      <u-icon name="woman" color="#fff" size="58" label="美颜" label-pos="bottom" label-color="#fff"></u-icon>

    </div>
  </div>
</div>
</template>

<script>

var isFirst = false
var timer = null;
let client_id, token;

let messagePool = [];
// 弹幕信息最多20条
let maxMessageCount = 20;
// 每次去弹幕池取出的条数
let maxMessageFrameCount = 5;
let setpraiseAction = null;
let onlineTimer = null;
let offScan = true;

export default {
  data() {
    return {
      fil: true,
      pushUrl: '',
      isPlay: false,
      pushWidth: uni.getSystemInfoSync().windowWidth,
      pushHeight: uni.getSystemInfoSync().windowHeight,
      isLoading: false,
      currentWebview: null,
      pusher: null,
      toIndex: 'A6',
      coderate: '',
      context: null,
      whitenessLevel: 0,
      isBeautiful: 0,
      mode: [],
      msgList: [],
      userAvatarList: [],
      liveMessage: '',
      liveCode: '',
      scrollTop: 0,
      scrollIntoView: '',
      systemNotice: '',
      roomId:null,
      switchCameraStatus:false
    }
  },
  watch:{
    // msgList(val) {
    //   if (val.length > 50) {
    //     this.$nextTick(() => {
    //       this.msgList.splice(0, 1);
    //     });
    //   }
    // }
  },
  onLoad(options) {
    client_id = uni.getStorageSync('client_id')
    token = uni.getStorageSync('token')
    console.log('options',options);
    this.context = uni.createLivePusherContext("livePusher", this);
    uni.getStorage({
      key: 'pushUrl',
      success: res => {
        this.pushUrl = res.data
      }
    })
    uni.setKeepScreenOn({
      keepScreenOn: true
    })
    this.context.startPreview(res => {

    })

    uni.getStorage({
      key: "openLiveID",
      success: res => {
        this.getLiveinformation(res.data)
      }
    });
    if(options.re == '1'){
      if(options.isPlay == '1'){
        console.log('恢復直播')
        this.startPusher();
      }
      if(options.switchCameraStatus == '1'){
        console.log('回復鏡頭');
        this.switchCamera();
      }
      // 恢复一下弹幕记录
      let messages =  uni.getStorageSync('LiveMessageRecords')
      console.log('重新開播',messages);

      this.msgList = messages;


    }
    uni.$on('WS_RC',()=>{
      console.log('主播重新进行连接ws1')
      uni.$emit('RE_LIVE',{isPlay:this.isPlay,switchCameraStatus:this.switchCameraStatus,messageRecords:this.msgList});
      uni.$off('WS_RC');
      uni.navigateBack({

      });
    });
  },
  onHide() {
  },

  methods: {
    loopMessagePool() {
      if(!offScan) return;
      console.log('扫描弹幕池')
      if (messagePool.length > 0) {
        let messages = messagePool.splice(0, maxMessageFrameCount);
        console.log('messages', messages);
        this.msgList = [...this.msgList, ...messages];
        this.$nextTick(() => {
          setTimeout(() => {
            this.go2bottom();
            if (this.msgList.length > 30) {
              this.msgList.splice(0, maxMessageFrameCount);
            }
          }, 50);
        });
        console.log(messagePool);
      }
      setTimeout(() => {
        this.loopMessagePool();
      }, 1000);
    },
    showActive(item){
      console.log('item',item);
    },
    getLiveinformation(e) {
      let data = {
        shop_id: e
      }
      this.$http.getLiveinformation(data).then(Res => {
        if (Res.status === 200) {
          this.systemNotice = Res.data.system_notice;
          this.roomId = Res.data.room;
          this.initWebSokcet(Res.data.room)
          this.loopMessagePool();
        }
      })
    },
    scroll(e) {

    },
    statechange(e) {
      console.log('e',e);

      this.liveMessage = e.detail.message;
      this.liveCode = e.detail.code
    },
    netstatus(e) {

    },
    error(e) {

    },

    close: function() {
      this.context.close({
        success: (a) => {

        }
      });
    },

    switchCamera() {
      this.switchCameraStatus = !this.switchCameraStatus;
      this.context.switchCamera((a) => {

      })
    },
    startPusher() {

      this.coderate = 'FHD'
      this.context.start(res => {

      })
      if (this.isPlay) {
        this.context.pause(res => {

        })
        this.coderate = ''
        this.isPlay = false
      } else {
        this.coderate = 'FHD'
        this.context.resume(res => {

        })
        this.isPlay = true
      }
    },

    changewhiteness() {
      if (this.whitenessLevel) {
        this.whitenessLevel = 0
      } else {
        this.whitenessLevel = 5
      }
    },

    beautiful() {
      if (this.isBeautiful) {
        this.isBeautiful = 0
      } else {
        this.isBeautiful = 5
      }
    },
    snapshot() {
      this.context.snapshot({
        success: (e) => {

          uni.saveImageToPhotosAlbum({
            filePath: e.tempImagePath,
            success: () => {

              uni.showToast({
                title: '已保存快照到本地相册',
              });
            }
          });

        }
      });
    },
    resume() {
      this.context.resume({
        success: (a) => {

        }
      });
    },
    pause() {
      this.context.pause({
        success: (a) => {

        }
      });
    },
    stop() {
      this.context.stop({
        success: (a) => {

        }
      });
    },
    initWebSokcet(room) {
      uni.sendSocketMessage({
        data: JSON.stringify({
          type: 'bindlive_id',
          id: token,
          room,
          client_id
        })
      });
      this.onWSMessage();
    },
    onWSMessage(){
      uni.onSocketMessage(res => {
        console.log('onSocketMessage res',res);
        const data = JSON.parse(res.data)
        if (data.type === "init") {
          let client_id = data.data.client_id
          console.log('new_client_id',client_id);
          uni.sendSocketMessage({
            data: JSON.stringify({
              type: 'bindlive_id',
              id: token,
              room:this.roomId,
              client_id: data.data.client_id
            })
          });
        }


        if (data.type === 'livesay') {
          console.log('监听到了 弹幕消息');
          messagePool.push(data.data);

          // this.msgList.push(data.data);
          // this.$nextTick(() => {
          //   setTimeout(() => {
          //     this.go2bottom();
          //   }, 50);
          // });
        }

        if (data.type === 'notice') {
          this.msgList.push({
            msg: data.msg
          });
          this.userAvatarList.unshift(data.data.headimgurl);
          this.$nextTick(() => {
            setTimeout(() => {
              this.go2bottom();
            }, 50);
          });
        }
      })
    },
    go2bottom() {
      const indicatorId = 'msg-' + (this.msgList.length - 1);
      this.scrollIntoView = indicatorId
    },
    scrolltolower(e) {
      this.offsetTop = e.currentTarget.offsetTop
    },

  }
}
</script>

<style lang="scss" scoped>
.livePusher {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.footerWrap {
  position: fixed;
  bottom: 50upx;

  display: flex;
  width: 100%;

  justify-content: space-between;

  .buticon {
    text-align: center;
    width: 25%;
    color: #fff;

    .buticon-img {
      width: 60upx;
    }
  }

}

.liveSayWrap {
  position: fixed;
  bottom: 150upx;
  left: 20upx;
  width: 500upx;
  overflow: hidden;
  height: 380upx;
  font-size: 24upx;
}

.tipwrap {
  @extend .item;
  color: #ff8534
}

.tagimg {
  width: 50upx;
  margin: 0 8upx;
}

view {
  font-size: 24upx;
}

.item {
  background-color: rgba(#000, 0.2);
  color: #FFF;
  padding: 2upx 10upx;
  border-radius: 10upx;
  font-size: 24upx;
  margin-bottom: 10upx;

  &-item {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
}

.username {
  color: #ff8534
}

.tip-scroller__tag {
  margin-right: 6rpx;
  margin-top: 4rpx;
  padding: 0 6rpx;
  font-size: 22rpx;
  height: 30rpx;
  line-height: 30rpx;
  text-align: center;
  color: #fff;
  border-radius: 10rpx;
  background-image: linear-gradient(to right, #ff6f0f, #fa3e3f);
}

.tip-scroller__member {
  background-image: linear-gradient(to right, #ff9900, #ffaf37);
}

.pusherNetStatus {
  position: fixed;
  top: 100upx;
  right: 30upx;
  background-color: rgba(#000, 0.5);
  border-radius: 4upx;
  color: #eee;
  font-size: 20upx;
}
</style>
